#
# @lc app=leetcode.cn id=543 lang=python3
#
# [543] 二叉树的直径
#

# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        ans = 0
        def dfs(node: Optional[TreeNode]) -> int:
            if node is None:
                return -1 # -1?0?
            left_len = dfs(node.left)
            right_len = dfs(node.right)
            nonlocal ans
            ans = max(left_len+right_len+2, ans)
            # 叶子节点 left_len=right_len=-1 left_len+right_len+2=0
            return max(left_len, right_len) + 1
        dfs(root)
        return ans
            
            
# @lc code=end

